package com.lsyonlygoddes.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:lsyonlygoddes
 * @time:2024/1/18 12:41
 */
@Slf4j
@Component
@ServerEndpoint("/ws/{cId}")
public class WebsocketServer {

    public static Map<String,Session> sessionMap=new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("cId")String cId) throws Exception {
        log.info("客户端 {} 连接成功",cId);
        sessionMap.put(cId,session);
    }

    @OnMessage
    public void onMessage(String msg){
        log.info("客户端消息是 {}",msg);
    }

    @OnClose
    public void onClose(Session session){
        log.info("有客户端关闭连接{}",session);
    }

    public void sendMsg() throws Exception {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            if (!session.isOpen()) continue;
            session.getBasicRemote().sendText("你好，客户端<br/>");
        }
    }
}
